<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="c_index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
              Divider(type="vertical")
              |应付总计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.total}}
              |元
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasExportApply" type="info" @click="exportApply") 导出
              Button.mr-10(v-if="hasExportApplyAllDetails" type="info" @click="exportApplyDetail") 导出明细
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(v-if="hasPostApplyUsers" type="text" @click="handleShowChooseEmployeeModal(row)") 申请发放
            Button(v-if="hasGetDetails" type="text" @click="gotoDetail(row)") 明细

    //- 选择员工弹窗
    ChooseEmployeeModal(ref="ChooseEmployeeModal" @uploadSuccess="query")
    //- //- 台账导入弹窗
    //- ImportStandingBookModal(ref="ImportStandingBookModal" @uploadSuccess="query")
    //- //- 付款弹窗
    //- PayModal(ref="PayModal" @query="query")
    //- //- 导出前弹窗
    //- ExportModal(ref="ExportModal" @query="query")
    //- //- 导出付款单弹窗
    //- ExportPDFModal(ref="ExportPDFModal" @query="query")
    //- //- 查看付款弹窗
    //- LookPayListModal(ref="LookPayListModal" @query="query")

    //- 流程审批单弹窗
    AuditDetailModal(ref="AuditDetailModal" @query="query")
    //- 选择审批方式弹窗
    //- ChooseTypeModal(ref="ChooseTypeModal" @query="query")
</template>

<script>
import { Common } from '@/utils/common.js'
import { FinancePayAccountApi } from '@/api/FinancePayAccount.api.js'
import { FinanceSPayableApi } from '@/api/FinanceSPayable.api.js'
import { ShouldPayableThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import ChooseEmployeeModal from './modal/chooseEmployeeModal.vue'
import AuditDetailModal from "../publicModal/auditDetailModal.vue"
// import ChooseTypeModal from "../publicModal/chooseTypeModal.vue"
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'sApplyList',

  components: {
    ChooseEmployeeModal,
    AuditDetailModal,
    // ChooseTypeModal
  },

  data () {
    return {
      // companyId: '', // 公司ID
      // companyName: '', // 公司名称
      // employeeId: '', // 员工ID
      thead: _cloneDeep(ShouldPayableThead),
      tableData: [],
      formData: {
        companyName: this.$route.query.commonNo || null,
        status: null,
        startDate: new Date(),
        endDate: new Date()
      },
      formItem: [
        { type: "input", label: "客户名称：", placeholder: "请输入客户名称", prop: "companyName", model: "companyName", style: "ivu-col-span-6" },
        { type: 'select', label: '状态：', placeholder: '请输入状态', prop: 'status', model: 'status', options: 'status', style: 'ivu-col-span-6' },
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'startDate', model1: 'startDate', placeholder2: '结束日期', prop2: 'endDate', model2: 'endDate', style: 'ivu-col-span-8' },
        { type: 'button', style: 'ivu-col-span-4' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 应付总计
      },
      downLoadRul: '',
      arrListDown: {
        securityNos: [],
        status: [
          // {label: '待申请', value: '1'},
          // // {label: '已申请', value: '2'},
          // {label: '已付款', value: '3'},
          // {label: '待付款', value: '4'}
        ],
        payAccount: [],
        PayType: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      isDelete: false
    }
  },

  watch: {
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasGetList () {
      return this.actionArr.indexOf('GetList') > -1
    },
    // 导出
    hasExportApply () {
      return this.actionArr.indexOf('ExportApply') > -1
    },
    // 导出明细
    hasExportApplyAllDetails () {
      return this.actionArr.indexOf('ExportApplyAllDetails') > -1
    },
    // 申请发放
    hasPostApplyUsers () {
      return this.actionArr.indexOf('PostApplyUsers') > -1
    },
    // 明细
    hasGetDetails () {
      return this.actionArr.indexOf('GetDetails') > -1
    },
    // 导出明细
    hasExportApplyAllDetails () {
      return this.actionArr.indexOf('ExportApplyAllDetails') > -1
    }
  },

  mounted () {
    this.getEnum()
    this.getEnum2()
    this.query()
  },

  methods: {
    getEnum () {
      let typeName = 'PayType'
      Common.getSelectIdList(typeName, this.arrListDown)
    },

    // 数据字典
    getEnum2 () {
      let groupName = 'financesalary.status'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        ...this.formData,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        startDate: this.formData.startDate ? this.$moment(this.formData.startDate).format('YYYY-MM'):'',
        endDate: this.formData.endDate ? this.$moment(this.formData.endDate).format('YYYY-MM'):'',
      }
      let res = await FinanceSPayableApi.getSApply(params)
      console.log('薪资付款申请res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.total = res.data.total
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (val) {
      console.log('val: ', val)
    },

    // 导出薪资付款申请
    async exportApply () {
      var params = {
        ...this.formData,
        // HasPaging: true,
        // PageIndex: this.tableComone.pageIndex,
        // PageSize: this.tableComone.pageSize,
        startDate: this.formData.startDate ? this.$moment(this.formData.startDate).format('YYYY-MM'):'',
        endDate: this.formData.endDate ? this.$moment(this.formData.endDate).format('YYYY-MM'):'',
        salaryIDs: this.selectedEmployeeId
        // salaryIDs: 'ssssssssssssssssssss'
      }
      let res = await FinanceSPayableApi.exportApply(params)
      console.log('导出薪资付款申请res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // exportApplyDetail
    async exportApplyDetail () {
      var params = {
        ...this.formData,
        // HasPaging: true,
        // PageIndex: this.tableComone.pageIndex,
        // PageSize: this.tableComone.pageSize,
        startDate: this.$moment(this.formData.startDate).format('YYYY-MM'),
        endDate: this.$moment(this.formData.endDate).format('YYYY-MM'),
        salaryIDs: this.selectedEmployeeId
        // salaryIDs: 'ssssssssssssssssssss'
      }
      let res = await FinanceSPayableApi.exportAllDetails(params)
      console.log('导出薪资付款申请明细res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 去往明细
    gotoDetail (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/sApplyDetail',
        name: 'sApplyDetail',
        query: {
          salaryID: row.id,
          companyID: row.customerGUID,
          customerName: row.customerName,
          legalName: row.legalName,
          salaryMonth: row.salaryMonth,
        }
      })
    },

    // 选择员工-显示弹窗
    handleShowChooseEmployeeModal (row) {
      this.$refs.ChooseEmployeeModal.isList = true
      this.$refs.ChooseEmployeeModal.modalKey = 'fromList'
      this.$refs.ChooseEmployeeModal.show(row)
      this.$refs.ChooseEmployeeModal.getApplyUsers()
    },

    // 选择审批方式-显示弹窗
    // handleShowChooseTypeModal() {
    //   this.$refs.ChooseTypeModal.show()
    //   this.$refs.ChooseTypeModal.modalType = '薪资付款申请'
    // },

    // 流程审批单-显示弹窗
    handleShowAuditDetailModal(row) {
      console.log('流程审批单-显示弹窗 row: ', row)
      this.$refs.AuditDetailModal.modalType = '薪资审批详情'
      this.$refs.AuditDetailModal.show(row)
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
